const {
    Keypair,
    Transaction,
    SystemProgram,
    LAMPORTS_PER_SOL,
    TransactionMessage,
} = require("@solana/web3.js");

const {
    getKeyPairUser1, getKeyPairUser2
} = require('./MyKeypair');

const config = require('./config');


const solChain = require('./SolChain');

const MpcVersionedTransaction = require('./MpcVersionedTransaction');
function transactionMessage(payerPubKey, recentBlockHash, instructions) {
    console.log('payerPubKey: ', payerPubKey);
    let messageV0 = new TransactionMessage({payerKey:payerPubKey, recentBlockhash:recentBlockHash, instructions:instructions}).compileToV0Message();
    const transaction = new MpcVersionedTransaction(messageV0);
    return transaction;
}

const sendTx = async () => {
    const fromKeypair = await getKeyPairUser1();
    const toKeypair = await getKeyPairUser2();

    console.log('fromKeypair: ', fromKeypair);

    //fromKeypair = Keypair.generate();

    //console.log('fromKeypair: ', fromKeypair);


    let instruction = SystemProgram.transfer({
        fromPubkey: fromKeypair.publicKey,
        toPubkey: toKeypair.publicKey,
        lamports: LAMPORTS_PER_SOL,
    });

    let latestBlockhash = await solChain.getLatestBlockhash();

    let payerPk = fromKeypair.publicKey;

    let tx = transactionMessage(payerPk, latestBlockhash.blockhash, [instruction]);
    console.log('tx: ', tx);


    let balance = await solChain.getBalance(fromKeypair.publicKey);
    console.log('from balance: ', balance);
    let tobalance = await solChain.getBalance(toKeypair.publicKey);
    console.log('to balance: ', tobalance);

    await tx.sign([fromKeypair]);
    let rawTx = tx.serialize();


    let ret = await solChain.sendRawTransaction(rawTx);
    console.log('ret: ', ret);

    //ret: 2X6nJry6NXN9QWfjiQ3dQirJ677qSfFFT4n8UQfTyq135jV48cEpAJ8uesUVGdYbgfMpbZNqdWP7CBtjJM4VZMh8
}
const get_tx = async ()=> {
    let solChain = new SolChain(config.devNodeUrl2);
    let ret = "2X6nJry6NXN9QWfjiQ3dQirJ677qSfFFT4n8UQfTyq135jV48cEpAJ8uesUVGdYbgfMpbZNqdWP7CBtjJM4VZMh8"
    let tx = await solChain.getTransaction(ret);

    console.log('tx: ', tx);
}
const getbalance = async () => {
    const fromKeypair = await getKeyPairUser1();
    const toKeypair = await getKeyPairUser2();


    let balance = await solChain.getBalance(fromKeypair.publicKey);
    console.log('from balance: ', balance);
    let tobalance = await solChain.getBalance(toKeypair.publicKey);
    console.log('to balance: ', tobalance);

}
//sendTx();
//get_tx();
getbalance();